const {
	http
} = require("../../utils/apiutils")
const app = getApp()
let ctxWidth = '';
let ctxHeight = '';
let ctx = null; //Camera
let canvaCtx = null; //canvas
var baidu = require('../../utils/bdutils.js')
var _this = this;
Component({
	properties: {
		bindthis: {
			type: Object
		}
	},
	options: {
		multipleSlots: true
	},
	data: {
		isca: true,
		info: {},
		baseImg: '',
		isCanvas: false,
		srcCanvasPath: "",
		isSuccess: false,
		isBaseImg: false,
		idcardInfo: {},


		userInfo: {},
		isF: false,
		flash: false,
		istak: 2,
		idcard: {
			sex: "男",
			realName: "", //姓名
			nation: "", // 民族
			birthday: "", // 出生日期
			address: "", // 家庭住址
			idNumber: "", // 身份证号
			phone: ''
		},
		xieyi: false,
		popShow: false,
		popShow2: false,
		prizeName: '',
		hasIdNumber:false,
	},
	ready() {
		this.changeText()
		console.log(this.data.bindthis)
	},
	methods: {
		getList() {
			this.targetEvent('getList')
		},
		changeText() {
			wx.getSystemInfo({
				success: res => {
					this.setData({
						info: res,
					})
				}
			})
		},
		takePhoto() {
			console.log("--------生成照片-------")
			ctx = wx.createCameraContext(); //初始化camera
			ctx.takePhoto({ //生成图片
				quality: 'high',
				success: (res) => { //得到图片
					this.takeCanvas(res.tempImagePath)
					this.setData({
						baseImg: res.tempImagePath,
						// isBaseImg: true,
						isCanvas: true
					})
				}
			})
		},
		takeCanvas(path) { //将拍摄的照片绘制到canvas上
			let _this = this;
			wx.getImageInfo({
				src: path,
				success: imgInfo => {
					let {
						info
					} = _this.data;
					let prxHeight = (info.windowHeight + 150) / imgInfo.height; //计算设备比
					let prxWidth = info.windowWidth / imgInfo.width; //计算设备比
					let convasX = imgInfo.width / 15;
					let canvasWidth = convasX * 13;
					let canvasHeight = convasX * 13 * 3 / 5;
					let convasY = (imgInfo.height - canvasHeight) / 2;
					// let convasXL = convasX / 2;
					// 我这里宽度和高度都计算了设备比，其实两个值是一样的 ，计算一个就够了
					// ctx = wx.createCanvasContext("myCanvas", _this);//自定义组件，需要加this
					canvaCtx = wx.createCanvasContext("myCanvas",_this); //自定义组件，需要加this
					// let a = (info.windowHeight - 150 - (info.windowWidth - 50) * 3 / 5) / 2
					console.log("-----------", imgInfo.width, imgInfo.height, convasX, convasY, canvasWidth, canvasHeight, prxWidth, prxHeight, (parseInt(canvasWidth) * prxWidth), (parseInt(canvasHeight) * prxHeight));
					canvaCtx.drawImage(path, convasX-10, convasY-130, canvasWidth+10, canvasHeight+20, 0, 0, canvasWidth * prxWidth, canvasHeight * prxHeight); //绘制到canvas上的位置，canvas的宽高等
					canvaCtx.draw(true, () => {
						wx.canvasToTempFilePath({
							fileType: "jpg",
							quality: 1,
							canvasId: "myCanvas",
							success: canvasToPath => {
								_this.setData({
									// baseImg: canvasToPath.tempFilePath,
									srcCanvasPath: canvasToPath.tempFilePath,
									isBaseImg: true,
									isSuccess: true,
									isca: false,
									// isCanvas:false,
								})
							}
						},_this)
						baidu.getoAuthToken();
						// wx.canvasToTempFilePath({
						//   fileType: "jpg",
						//   quality: 0.3,
						//   canvasId: "myCanvas",
						//   success: canvasToPath => {
						//     this.setData({
						//       isBaseImg: false,
						//       baseImg: canvasToPath.tempFilePath,
						//       srcCanvasPath: canvasToPath.tempFilePath
						//     })
						//   }
						// }, this)//自定义组件需要加this
					})
				}
			})
		},
		takePhoto1: function () {
			var that = this;
			baidu.getoAuthToken();
			wx.chooseImage({
				count: 1, // 最多可以选择的图片张数，默认9
				sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
				sourceType: ['album'], // album 从相册选图，camera 使用相机，默认二者都有
				success: function (res) {
					// success
					that.data.srcCanvasPath = res.tempFilePaths[0];
					that.confirmBack();
				},
				fail: function () {
					// fail
				},
				complete: function () {
					// complete
				}
			})
		},
		confirmBack: function () {

			var base64 = 'data:image/jpg;base64,' + wx.getFileSystemManager().readFileSync(this.data.srcCanvasPath, "base64");
			// console.log("----", base64);
			var data = {
				image: base64,
				id_card_side: "front",
			}
			this.baiduUpdate(data)

		},
		baiduUpdate: function (data) {
			var that = this;
			baidu.sumbitImgToBadu(data,
				function (res) {
					console.log("----返回照片的信息---", res);
					if (res.image_status != "normal") {
						var str = "未知状态"
						if (res.image_status == "reversed_side") {
							str = "身份证正反面颠倒"
						} else if (res.image_status == "non_idcard") {
							str = "上传的图片中不包含身份证"
						} else if (res.image_status == "blurred") {
							str = "身份证模糊"
						} else if (res.image_status == "other_type_card") {
							str = "其他类型证照"
						} else if (res.image_status == "over_exposure") {
							str = "身份证关键字段反光或过曝"
						} else if (res.image_status == "other_type_card") {
							str = "其他类型证照"
						} else if (res.image_status == "over_dark") {
							str = "身份证欠曝（亮度过低）"
						} else {
							str = "未知错误"
						}
						wx.showModal({
							title: '识别错误',
							content: str,
							showCancel: false,
							confirmText: "我知道了",
							success(res) {
								that.clearPhoto()
							}
						})
						return;
					}
					if (res.words_result) {
						let w = res.words_result;
						var idNumber = "",
							name = "",
							nativePlace = "",
							nation = "",
							sex = "";
						if (w["公民身份号码"] && w["公民身份号码"].words != "") {
							idNumber = w["公民身份号码"].words;
						} else {
							wx.showModal({
								title: '识别错误',
								content: "未检查到身份证号",
								showCancel: false,
								confirmText: "我知道了",
								success(res) {
									that.clearPhoto()
								}
							})
							return;
						}
						if (w["姓名"] && w["姓名"].words != "") {
							name = w["姓名"].words;
						} else {
							wx.showModal({
								title: '识别错误',
								content: "未检查到姓名",
								showCancel: false,
								confirmText: "我知道了",
								success(res) {
									that.clearPhoto()
								}
							})
							return;

						}
						if (w["住址"] && w["住址"].words != "") {
							nativePlace = w["住址"].words;
						} else {
							wx.showModal({
								title: '识别错误',
								content: "未检查到住址",
								showCancel: false,
								confirmText: "我知道了",
								success(res) {
									that.clearPhoto()
								}
							})
							return;

						}
						if (w["民族"] && w["民族"].words != "") {
							nation = w["民族"].words;
						} else {
							wx.showModal({
								title: '识别错误',
								content: "未检查到民族",
								showCancel: false,
								confirmText: "我知道了",
								success(res) {
									that.clearPhoto()
								}
							})
							return;
						}
						if (w["性别"] && w["性别"].words != "") {
							sex = w["性别"].words;
						} else {
							wx.showModal({
								title: '识别错误',
								content: "未检查到性别",
								showCancel: false,
								confirmText: "我知道了",
								success(res) {
									that.clearPhoto()
								}
							})
							return;
						}

						var birthday = ""
						if (idNumber.length == 15) {
							birthday = "19" + idNumber.substr(6, 6);
						} else if (idNumber.length == 18) {
							birthday = idNumber.substr(6, 8);
						}
						var data = {
							sex: sex,
							realName: name, //姓名
							nation: nation, // 民族
							birthday: birthday, // 出生日期
							address: nativePlace, // 家庭住址
							idNumber: idNumber // 身份证号
						}
						wx.showToast({
							title: '识别成功请确认信息',
							icon: "none",
							success() {
								that.setData({
									idcardInfo:data
								})
								wx.nextTick(_ => { 
									that.returnIdcard()
								})
							}
						})
					} else {
						wx.showModal({
							title: '识别错误',
							content: "身份认证失败",
							showCancel: false,
							confirmText: "我知道了",
							success(res) {
								that.clearPhoto()
							}
						})
					}
				},
				function (err) {
					wx.showToast({
						title: '身份认证失败',
						icon: "none",
					})
				})
		},
		clearPhoto() {
			// canvaCtx.clearRect(0,0,ctxWidth, ctxHeight)
			// canvaCtx.draw()
			this.setData({
				srcCanvasPath: "",
				isCanvas: false,
				isSuccess: false,
				isBaseImg: false,
				isca: true,
			})
		},
		returnIdcard() { 
			console.log(111111,this.data.idcardInfo)
			this.triggerEvent('idCardData',this.data.idcardInfo)
		}
	}
})